import { getLoginCode, login, loginOut } from '@/services/login';
import { loginBack } from '@/utils/loginBack';
import Taro from '@tarojs/taro';

export default {
  namespace: 'login',
  state: {
    sendResult: false,
    openId: null,
  },
  effects: {
    *login({ payload, headers }, { call, put }) {
      const res = yield call(login, payload, headers);
      if (res.code === '1') {
        Taro.showToast({
          title: '登录成功',
        });
        if (res.content?.openId) {
          yield put({
            type: 'setOpenId',
            payload: res.content.openId,
          });
          Taro.setStorageSync(
            'auth',
            JSON.stringify({
              openId: res.content.openId,
            }),
          );
        }
        const timestamp = new Date().getTime();
        Taro.setStorageSync(
          'user',
          JSON.stringify({
            user: res.content,
            loginType: payload.loginType,
            timestamp,
          }),
        );

        yield put({
          type: 'user/getUserInfo',
        });

        loginBack();
      }
    },
    *loginByWallet({ payload }, { call }) {
      const res = yield call(login, payload);
      if (res.code === '1') {
        const timestamp = new Date().getTime();
        Taro.setStorageSync(
          'user',
          JSON.stringify({
            user: res.content,
            timestamp,
          }),
        );
        return;
      } else {
        return Promise.reject();
      }
    },
    *getCode({ payload }, { call, put }) {
      const res = yield call(getLoginCode, payload);
      if (res.code === '1') {
        yield put({
          type: 'codeSend',
          payload: true,
        });
      }
    },

    *getOpenId({ payload }, { call, put }) {
      let res = yield call(login, payload);
      const { code, content } = res;
      if (code === '1') {
        let openId = content.openId;
        yield put({
          type: 'setOpenId',
          payload: openId,
        });
        Taro.setStorageSync(
          'auth',
          JSON.stringify({
            openId,
          }),
        );
      } else {
        return Promise.reject();
      }
    },

    *loginOut({ payload }, { call }) {
      const res = yield call(loginOut, payload);
      if (res.code === '1') {
        Taro.showToast({
          title: '退出登录成功',
          icon: 'none',
        });
        Taro.clearStorageSync();
        Taro.navigateTo({
          url: '/pages/other/login/index',
        });
      } else {
        Taro.showToast({
          title: '退出登录失败',
          icon: 'none',
        });
      }
    },
  },
  reducers: {
    codeSend(state, { payload }) {
      return {
        ...state,
        sendResult: payload,
      };
    },
    setOpenId(state, { payload }) {
      return {
        ...state,
        openId: payload,
      };
    },
  },
};
